package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/validateCode/")
public class ValidateCodeController {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public static final String REGISTERED_KEY = "HEALTH_REGISTERED";
    public static final String LOGIN_KEY = "HEALTH_LOGIN";

    @RequestMapping("send4Order")
    public Result send4Order(String telephone){
        try {

            String code = ValidateCodeUtils.generateValidateCode4String(4);


            SMSUtils.sendSms(SMSUtils.VALIDATE_CODE,telephone.toString(), JSON.parse("{'code':'"+code+"'}").toString());

            //根据手机存Redis  时间存储  15分钟
            redisTemplate.opsForValue().set(REGISTERED_KEY+telephone,code,15, TimeUnit.MINUTES);


            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
    @RequestMapping("send4Login")
    public Result send4Login(String telephone){
        try {

            String code = ValidateCodeUtils.generateValidateCode4String(6);


            SMSUtils.sendSms(SMSUtils.VALIDATE_CODE,telephone.toString(), JSON.parse("{'code':'"+code+"'}").toString());

            //根据手机存Redis  时间存储  15分钟
            redisTemplate.opsForValue().set(LOGIN_KEY+telephone,code,15, TimeUnit.MINUTES);


            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }


}
